学习了些人工智能的东西, 利用遗传算法来写了一个寻路的演示程序, 虽然该算法效率底下, 但作为一个学习程序还是有直观性;
先把代码和结果贴上, 有时间再写分析
遗传算法类
主要有两个类: 基因编码类和基因组类;
"GeGroup.h"
#ifndef _GEGROUP_HBB_
#define _GEGROUP_HBB_
#include "HMap.h"
#include "Global.h"
#include <bitset>
class HMap;
class GeCode
{
public:
GeCode();
~GeCode();
std::bitset<LEN_BIT_ROUTE> mGeRoute;
int mHighestFitSce;
int mHighestSceStep;
void Clear();
// decode generic
SearchDir DeCode(const int StepIndex);
};
class GeGroup
{
public:
GeGroup(HMap& m);
~GeGroup();
GeCode mGrop[NUM_GEGROUP];
GeCode mFitGes[NUM_GEGROUP];
int mBestGeIndex;
int mTotalFitSce;
HMap& mMap;
bool Epoch();
bool UpdateFitnessScore();
GeCode WheelSelect();
private:
int mGenerationCount;
static const int mMaxScore = NUM_MAX_GRID*NUM_MAX_GRID*4;
inline bool IsCrossOver(){return RandInt(0,10) <= RATE_CROSSOVER;}
inline bool IsMutation(){return RandInt(0,1000) <= RATE_MUTATION;}
int CalcuFitScore(const int idx);
int CalcuPosScore(const point& p);
void CrossOver(const int mom, const int dad);
void Mutate(const int geLst);
bool EvolutionSelection();
void ShowMarkMap();
};
#endif // _GEGROUP_HBB_
"GeGroup.cpp"
#include "GeGroup.h"
#include <cassert>
#include <iostream>
#include "HMap.h"
#include <stdlib.h>
using namespace std;
static const int MAX_INT = 0x7fffffff;
GeCode::GeCode():mHighestFitSce(0),mHighestSceStep(0)
{
}
GeCode::~GeCode(){}
SearchDir GeCode::DeCode(const int StepIndex)
{
int codePos = StepIndex*LEN_BIT_CODE;
unsigned Dir = 0;
Dir |= (1u&mGeRoute[codePos]) | ((1u&mGeRoute[codePos+1])<<1) | ((1u&mGeRoute[codePos+2])<<2);
return (SearchDir)Dir;
}
void GeCode::Clear()
{
for(int i = 0; i < LEN_BIT_ROUTE; ++i)
mGeRoute[i] = 0;
mHighestSceStep = 0;
mHighestFitSce = 0;
}
/*******************************
/// class GeGroup
*******************************/
GeGroup:: GeGroup(HMap& m):mBestGeIndex(0),mTotalFitSce(0)
,mMap(m),mGenerationCount(0)
{
for(int i = 0; i < NUM_GEGROUP;++i)
{
for(int j = 0; j<LEN_BIT_ROUTE;++j)
mGrop[i].mGeRoute[j] = RandInt(0,1);
}
}
GeGroup::~ GeGroup()
{
//dtor
}
int GeGroup::CalcuPosScore(const point& p)
{
// the longer distance, the lower score
return 10000/ (abs(p.x - mMap.Ep.x) + abs(p.y - mMap.Ep.y)+1);
}
// calculate the fitness score, and record t